package com.example.addressbook;

import android.widget.*;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; 
import android.content.Intent; 
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.LayoutInflater;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.LinearLayoutManager;
import android.provider.CallLog;
import android.database.Cursor;
import android.content.ContentResolver;
import android.support.v4.content.ContextCompat;
import android.support.v4.app.ActivityCompat;
import android.content.pm.PackageManager; 
import android.Manifest;
import android.widget.Button;
import android.graphics.Color;
import android.net.Uri; 
 
import java.util.*;
import java.text.*;

public class ListFragment1 extends Fragment{
	
	private RecyclerView recyclerView;
	public CallLogAdapter callLogAdapter;
	
	@Override
	public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
		
		View view = inflater.inflate(R.layout.list_fragment_1,container,false);
		callLogAdapter = new CallLogAdapter(getActivity(),getDataList());
		recyclerView = (RecyclerView)view.findViewById(R.id.recycler_view_0);
		recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
		recyclerView.setAdapter(callLogAdapter);
		 fab = (FloatingActionButton)view.findViewById(R.id.fab);
		fab.setColorFilter(Color.WHITE);
		
		
		return view;
		
	}
	
		FloatingActionButton fab;
	
	@Override
	public void onResume(){
		//Toast.makeText(getActivity(),"fragment_1_onResume",Toast.LENGTH_SHORT).show();
		callLogAdapter.query(getDataList());
		
		fab.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v){
					String telNumber = callLogAdapter.getFirstTelephone();
					
					Intent intent = new Intent(Intent.ACTION_DIAL);
					intent.setData(Uri.parse("tel:"+telNumber));
					getActivity().startActivityForResult(intent,3);
					getActivity().overridePendingTransition(android.R.anim.slide_in_left,
																		android.R.anim.slide_out_right);
			}
		});
		super.onResume();
	}
	
	private static int year = Calendar.getInstance().get(Calendar.YEAR); 
	
	private List< Map<String, String> > getDataList() {
		// 1.获得ContentResolver
		ContentResolver resolver = getActivity().getContentResolver();
		// 2.利用ContentResolver的query方法查询通话记录数据库
		/**
		 * @param uri 需要查询的URI，（这个URI是ContentProvider提供的）
		 * @param projection 需要查询的字段
		 * @param selection sql语句where之后的语句
		 * @param selectionArgs ?占位符代表的数据
		 * @param sortOrder 排序方式
		 * 
		 */
		Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, // 查询通话记录的URI
			new String[] { CallLog.Calls.CACHED_NAME// 通话记录的联系人
				, CallLog.Calls.NUMBER// 通话记录的电话号码
				, CallLog.Calls.DATE// 通话记录的日期
				, CallLog.Calls.DURATION// 通话时长
				, CallLog.Calls.TYPE }// 通话类型
			, null, null, CallLog.Calls.DEFAULT_SORT_ORDER// 按照时间逆序排列，最近打的最先显示
		);
		// 3.通过Cursor获得数据
		List< Map<String, String> > list = new ArrayList<Map<String, String>>();
		while( cursor.moveToNext() ){
			String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
			String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
			long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
			  String date = new SimpleDateFormat("yyyy/MM/dd  HH:mm:ss").format(new Date(dateLong));
			  if( Integer.parseInt( date.substring(0,4) ) == year ){
				  date = date.substring(5);
			  }
			  int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
			  int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
			  String typeString = "";
			  switch (type) {
				case CallLog.Calls.INCOMING_TYPE:
					typeString = "接入";
					break;
				case CallLog.Calls.OUTGOING_TYPE:
					typeString = "打出";
					break;
				case CallLog.Calls.MISSED_TYPE:
					typeString = "拒接";
					break;
				default:
					break;
		}
		Map<String, String> map = new HashMap<String, String>();
		if( name != null && name.length() > 7 ) name = name.substring(0,7)+"…";
		map.put("name", name);//name == null) ? "未知联系人" : name);
		map.put("number", number);
		map.put("date", date);
		map.put("duration", new Integer(duration).toString());//(duration / 60) + "分"+(duration%60)+"秒");
		map.put("type", typeString);
		list.add(map);
		}
		return list;
	}
}